package com.smartResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Geocoder;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class LocationMap extends MapActivity  
{

	 MapView mapView; 
	 String address_raw;
	 String address_parse;
	 static double lng;
	 static double lat;
	 static double rad; // radius to be saved
	 GeoPoint p;
	 
    /** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState){
	    	super.onCreate(savedInstanceState);
	    	setContentView(R.layout.mapview);
	
	        mapView = (MapView) findViewById(R.id.l_mapview);
	        mapView.setBuiltInZoomControls(true);
	        address_raw = "None Entered";
	        rad = 250;
	        
	        Drawable marker = getResources().getDrawable(R.drawable.map_marker); 
	        marker.setBounds((-marker.getIntrinsicWidth()/2),
	        		-marker.getIntrinsicHeight(),
	        		(marker.getIntrinsicWidth()/2), 
	        		0);
	        
	        mapOverlay myOverlay = new mapOverlay(marker);
	        List<Overlay> overlays = mapView.getOverlays();        
	        overlays.add(myOverlay);
	    	
	        Button btnSearch = (Button) findViewById(R.id.Search);
	        btnSearch.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					EditText txtSearch=(EditText)findViewById(R.id.l_place);			
					address_raw = txtSearch.getText().toString();
					LocationMap.this.changeMap(address_raw);
				}
			});
	    }
	    
	@Override
	protected boolean isRouteDisplayed() 
	{
		return false;
	}

	public void changeMap(String area)
	{
        mapView = (MapView) findViewById(R.id.l_mapview);
        MapController mc = mapView.getController();

        GeoPoint myLocation = null;
        lat = 0;
        lng = 0;
        
        try
        {
        	Geocoder g = new Geocoder(this, Locale.getDefault()); 
        	Log.d("area",area);
            java.util.List<android.location.Address> result = g.getFromLocationName(area, 1); 
            
            if(result.size()>0) {
            	lat = result.get(0).getLatitude();
            	lng = result.get(0).getLongitude();
            	Toast.makeText(LocationMap.this, "Latitude is: " + lat + "\n" + "Longitude is: " + lng, Toast.LENGTH_SHORT).show();
            	Log.d("result",result.toString());
            } 
            else {
            	Toast.makeText(LocationMap.this, "record not found", Toast.LENGTH_SHORT).show();
            	return;
            }
        }
        catch(IOException io)
        {
        	//Toast.makeText(LocationMap.this, "Connection Error", Toast.LENGTH_SHORT).show();
        	Toast.makeText(LocationMap.this, io.toString(), Toast.LENGTH_LONG).show();
        }
        
        myLocation = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));
        mc.animateTo(myLocation);
        mc.setZoom(18); 
    	Toast.makeText(LocationMap.this, "Latitude is: " + lat + "\n" + "Longitude is: " + lng, Toast.LENGTH_SHORT).show();
        mapView.invalidate();
	}
	
    public void viewClickHandler(View target) {
    	switch(target.getId()) {
    	case R.id.sat_view:
    		mapView.setSatellite(true);
    		break;
    	case R.id.normal_view:
    		mapView.setSatellite(false);
    		mapView.setTraffic(false);
    		break;
    	case R.id.change_radius:
    		// change the default radius for drawing here
    		AlertDialog.Builder alert = new AlertDialog.Builder(this);

    		alert.setTitle("Change Radius");
    		alert.setMessage("Current Radius: " + rad + " feet");

    		// Set an EditText view to get user input 
    		final EditText input = new EditText(this);
    		input.setInputType(InputType.TYPE_CLASS_NUMBER);
    		input.setText(String.valueOf(rad));
    		alert.setView(input);
    		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    		public void onClick(DialogInterface dialog, int whichButton) {
	    			String value = input.getText().toString();
	    			Log.d("value",value);
	    			if (value.length() == 0){
	    				
	    			}
	    			if (value.length() != 0){
	    			Double newRadius = Double.parseDouble(value);
	    			rad = newRadius;
	    			}
	    		}
    		});

    		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    		  public void onClick(DialogInterface dialog, int whichButton) {
    		    // Canceled.
    		  }
    		 
    		});

    		alert.show();
    		break;
    	case R.id.save_location:
    		Intent in = new Intent();
       	 	Bundle bundle = getIntent().getExtras();
       	 	String activity = bundle.getString("Activity");
       	 	Log.d("activity",activity);
       	 	if (activity.equals("AddLocation")){
       	 		AddLocation.setLocationVars(lat,lng,address_raw,rad,true); 
       	 	}
       	 	if (activity.equals("EditLocation")){
       	 		EditLocation.setLocationVars(lat,lng,address_raw,rad,true); 
       	 	}
       	 	setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
		    finish();
    	}
    	
    	// This line is necessary DO NOT DELETE
    	// It is a known issue with android and must be here to work properly
    	mapView.postInvalidateDelayed(2000);
    }

	/* This class uses an ItemizedOverlay for drawing a map marker on the MapView where a user taps the map. 
	 * */
	class mapOverlay extends ItemizedOverlay<OverlayItem> {
		private ArrayList<OverlayItem> location = new ArrayList<OverlayItem>();
		private Paint innerPaint;
		private Paint borderPaint;
		private GeoPoint clickedPoint;
		private float feetInMeters = (float) 3.2808399;
		
		
		
		public mapOverlay(Drawable marker) {
			super(marker);
			populate();
		}
		
		@Override
		public boolean onTap(GeoPoint p, MapView mapView) {
			clickedPoint = p;
			
			Toast.makeText(getBaseContext(),p.getLatitudeE6()/1E6 + "," + p.getLongitudeE6()/1E6, Toast.LENGTH_SHORT).show();
			lat = (p.getLatitudeE6()/1E6);
			lng = (p.getLongitudeE6()/1E6);
			
			if(!location.isEmpty())
				location.clear();
			
			location.add(new OverlayItem(p,"",""));
			populate();
			return true;
		}
		
		protected void drawCircle(Canvas canvas, GeoPoint p) {
			Point screenCoords = new Point();
			int radius = 0; // the radius in pixels that will be given to  the drawCircle() method
			
			// get the screen coordinates for the GeoPoint p so the circle can be drawn at that point.
			try {
				Projection proj = mapView.getProjection();
				proj.toPixels(p, screenCoords);
				radius = (int)(proj.metersToEquatorPixels((float)rad/feetInMeters));
				canvas.drawCircle((screenCoords.x), (screenCoords.y), radius, getInnerPaint());
				canvas.drawCircle((screenCoords.x), (screenCoords.y), radius, getBorderPaint());
			} catch (Exception e) { 
				//Log.d("Map",e.toString());
			}
		}
		
		public Paint getInnerPaint() {
		    if (innerPaint == null) {
		        innerPaint = new Paint();
		        innerPaint.setARGB(40, 0, 0, 175);
		        innerPaint.setAntiAlias(true);
		    }
		    return innerPaint;
		}
		public Paint getBorderPaint() {
			if (borderPaint == null) {
		        borderPaint = new Paint();
		        borderPaint.setARGB(180, 0, 0, 175);
		        borderPaint.setAntiAlias(true);
		        borderPaint.setStyle(Style.STROKE);
		        borderPaint.setStrokeWidth(1);
		    }
			return borderPaint;
		}
		
		@Override
		public void draw(Canvas canvas, MapView mapview, boolean shadow) {
			super.draw(canvas, mapview, shadow);
			drawCircle(canvas,clickedPoint);
		}
		
		@Override
		protected OverlayItem createItem(int i) {
			return location.get(i);
		}

		@Override
		public int size() {
			return location.size();
		}
		
	}
	//This code controls what happens when the back key is pressed
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    		Intent in = new Intent();
       	 	Bundle bundle = getIntent().getExtras();
       	 	String activity = bundle.getString("Activity");
       	 	Log.d("activity",activity);
       	 	if (activity.equals("AddLocation")){
       	 		AddLocation.setLocationVars(lat,lng,address_raw,rad,false); 
       	 	}
       	 	if (activity.equals("EditLocation")){
       	 		EditLocation.setLocationVars(lat,lng,address_raw,rad,false); 
       	 	}
       	 	setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
		    finish();
	    }

	    return super.onKeyDown(keyCode, event);
	}
	// Menu Layout
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0,1,0,"Home").setIcon(R.drawable.home);
        menu.add(0,2,0,"Save").setIcon(R.drawable.add_icon);
        menu.add(0,3,0,"Cancel").setIcon(R.drawable.cancel);
	    return true;
	}
    @Override
     public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
			  Intent home_intent_menu = new Intent(LocationMap.this, MainActivity.class);
			  startActivity(home_intent_menu);
			  
			  return true;
        case 2:
    		Intent in = new Intent();
       	 	Bundle bundle = getIntent().getExtras();
       	 	String activity = bundle.getString("Activity");
       	 	Log.d("activity",activity);
       	 	if (activity.equals("AddLocation")){
       	 		AddLocation.setLocationVars(lat,lng,address_raw,rad,true); 
       	 	}
       	 	if (activity.equals("EditLocation")){
       	 		EditLocation.setLocationVars(lat,lng,address_raw,rad,true); 
       	 	}
       	 	setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
		    finish();
        	

            return true;
     case 3:
	        finish();
            return true;
          }
		return false;
    }
}